package csharp.cauth.commands;

import java.util.logging.Level;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.PlayerInventory;

import com.nijiko.permissions.PermissionHandler;

import csharp.cauth.CAuth;
import csharp.cauth.Language;
import csharp.cauth.PlayersSL;
import csharp.cauth.PluginConfig;
import csharp.cauth.properties.InventoryProp;
import csharp.cauth.properties.PlayerProp;
import csharp.cauth.utils.Log;
import csharp.cauth.utils.MD5;

/**
 * @author Ярослав (CSharp) "/cauth" command. For OPs.
 */
public class CACAuth implements CommandExecutor
{
	private final CAuth plugin;

	public CACAuth(CAuth instance)
	{
		plugin = instance;
	}

	@Override
	public boolean onCommand(CommandSender sender, Command command,
			String label, String[] split)
	{
		if (sender instanceof Player)
		{
			Player player = (Player) sender;

			if (PluginConfig.usePermissions)
				return permissionsExecutor(player, split);
			else
				return executor(player, split);
		}

		return true;
	}

	private boolean executor(Player player, String[] split)
	{
		if (player.isOp())
		{
			if (split.length > 0)
			{
				if (split[0].equalsIgnoreCase("reset")) // Password resetting.
				{
					if (split.length > 1)
					{
						PlayerProp temp = null;

						for (PlayerProp playerProp : CAuth.players)
						{
							if (playerProp.getLogin().equalsIgnoreCase(
									split[1].toLowerCase()))
							{
								temp = playerProp;

								break;
							}
						}

						if (temp != null)
						{
							temp.setPassword(MD5.getHash(temp.getLogin()));

							if (PluginConfig.useMySQL)
								PlayersSL.updatePassword(temp.getId(),
										temp.getPassword());
							else
								PlayersSL.savePlayers();

							player.sendMessage("[CAuth] "
									+ Language.PASSWORD_SUCCESSFULLY_CLEARED);

							return true;
						}
						else
						{
							player.sendMessage("[CAuth] "
									+ Language.NO_PLAYER_WITH_THIS_LOGIN);

							return true;
						}
					}
				}
				else if (split[0].equalsIgnoreCase("remove")) // Registration
																// removing.
				{
					if (split.length > 1)
					{
						PlayerProp temp = null;

						for (PlayerProp playerProp : CAuth.players)
						{
							if (playerProp.getLogin().equalsIgnoreCase(
									split[1].toLowerCase()))
							{
								temp = playerProp;

								break;
							}
						}

						if (temp != null)
						{
							temp.setLastLoc(player.getWorld()
									.getSpawnLocation());

							CAuth.players.remove(temp);

							Player tempPlayer = plugin.getServer().getPlayer(
									temp.getLogin());

							if (tempPlayer != null
									&& CAuth.authorized.contains(tempPlayer))
							{
								CAuth.authorized.remove(tempPlayer);

								try
								{
									PlayerInventory inventory = tempPlayer
											.getInventory();

									CAuth.unauthorized.put(tempPlayer,
											new InventoryProp(inventory));

									inventory.clear();
									inventory.setBoots(null);
									inventory.setChestplate(null);
									inventory.setHelmet(null);
									inventory.setLeggings(null);
								}
								catch (Exception e)
								{
									/* Nothing TODO */
								}
							}

							String ip = temp.getIp();

							if (CAuth.ipCounter.containsKey(ip))
							{
								Integer count = CAuth.ipCounter.get(ip);

								CAuth.ipCounter.put(ip, count - 1);
							}

							if (PluginConfig.useMySQL)
								PlayersSL.remove(temp.getId());
							else
								PlayersSL.savePlayers();

							player.sendMessage("[CAuth] "
									+ Language.REGISTRATION_REMOVED);

							return true;
						}
						else
						{
							player.sendMessage("[CAuth] "
									+ Language.NO_PLAYER_WITH_THIS_LOGIN);

							return true;
						}
					}
				}
				else if (split[0].equalsIgnoreCase("reload")) // Configuration
																// reloading
				{
					CAuth.loadConfiguration();

					player.sendMessage("[CAuth] "
							+ Language.CONFIGURATION_RELOADED);

					return true;
				}
			}

			return false;
		}

		return true;
	}

	private boolean permissionsExecutor(Player player, String[] split)
	{
		PermissionHandler permissionHandler = CAuth.permissionHandler;

		if (permissionHandler == null)
		{
			Log.log(Level.INFO,
					"No permissions plugin installed, default command executor selected.");

			PluginConfig.usePermissions = false;

			return executor(player, split);
		}

		if (split.length > 0)
		{
			if (split[0].equalsIgnoreCase("reset")
					&& permissionHandler.has(player, "CAuth.cauth.reset")) // Password
																			// resetting.
			{
				if (split.length > 1)
				{
					PlayerProp temp = null;

					for (PlayerProp playerProp : CAuth.players)
					{
						if (playerProp.getLogin().equalsIgnoreCase(
								split[1].toLowerCase()))
						{
							temp = playerProp;

							break;
						}
					}

					if (temp != null)
					{
						temp.setPassword(MD5.getHash(temp.getLogin()));

						if (PluginConfig.useMySQL)
							PlayersSL.updatePassword(temp.getId(),
									temp.getPassword());
						else
							PlayersSL.savePlayers();

						player.sendMessage("[CAuth] "
								+ Language.PASSWORD_SUCCESSFULLY_CLEARED);

						return true;
					}
					else
					{
						player.sendMessage("[CAuth] "
								+ Language.NO_PLAYER_WITH_THIS_LOGIN);

						return true;
					}
				}
			}
			else if (split[0].equalsIgnoreCase("remove")
					&& permissionHandler.has(player, "CAuth.cauth.remove")) // Registration
																			// removing.
			{
				if (split.length > 1)
				{
					PlayerProp temp = null;

					for (PlayerProp playerProp : CAuth.players)
					{
						if (playerProp.getLogin().equalsIgnoreCase(
								split[1].toLowerCase()))
						{
							temp = playerProp;

							break;
						}
					}

					if (temp != null)
					{
						temp.setLastLoc(player.getWorld().getSpawnLocation());

						CAuth.players.remove(temp);

						Player tempPlayer = plugin.getServer().getPlayer(
								temp.getLogin());

						if (tempPlayer != null
								&& CAuth.authorized.contains(tempPlayer))
						{
							CAuth.authorized.remove(tempPlayer);

							try
							{
								PlayerInventory inventory = tempPlayer
										.getInventory();

								CAuth.unauthorized.put(tempPlayer,
										new InventoryProp(inventory));

								inventory.clear();
								inventory.setBoots(null);
								inventory.setChestplate(null);
								inventory.setHelmet(null);
								inventory.setLeggings(null);
							}
							catch (Exception e)
							{
								/* Nothing TODO */
							}
						}

						String ip = temp.getIp();

						if (CAuth.ipCounter.containsKey(ip))
						{
							Integer count = CAuth.ipCounter.get(ip);

							CAuth.ipCounter.put(ip, count - 1);
						}

						if (PluginConfig.useMySQL)
							PlayersSL.remove(temp.getId());
						else
							PlayersSL.savePlayers();

						player.sendMessage("[CAuth] "
								+ Language.REGISTRATION_REMOVED);

						return true;
					}
					else
					{
						player.sendMessage("[CAuth] "
								+ Language.NO_PLAYER_WITH_THIS_LOGIN);

						return true;
					}
				}
			}
			else if (split[0].equalsIgnoreCase("reload")
					&& permissionHandler.has(player, "CAuth.cauth.reload")) // Configuration
																			// reloading
			{
				CAuth.loadConfiguration();

				player.sendMessage("[CAuth] " + Language.CONFIGURATION_RELOADED);

				return true;
			}
			else
			{
				player.sendMessage("[CAuth] "
						+ Language.YOU_CANT_USE_THIS_COMMAND);

				return true;
			}
		}

		return false;
	}
}
